package com.example.lion.iot;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.view.LineChartView;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class TempActivity extends AppCompatActivity {
    private TextView txtTemp;
    private TextView txtTime;

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Log.v("m",msg.obj.toString());

            try {
                JSONObject jsonObjectResult = new JSONObject(msg.obj.toString());
                String strResult=jsonObjectResult.getString("results");
                Log.v("strResult",strResult);

                JSONArray jsonArray = new JSONArray(strResult);

                List<PointValue> yValues = new ArrayList<PointValue>();
                List<AxisValue> xValues = new ArrayList<AxisValue>();


                for(int i=0;i<jsonArray.length();i++){
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String time=jsonObject.getString("time");
                    String value=jsonObject.getString("value");
                    Log.v("time",time);
                    Log.v("value",value);
                    yValues.add(new PointValue(i, Float.parseFloat(value)));
                    xValues.add(new AxisValue(i).setLabel(time));


                    if(i==jsonArray.length()-1){
                        // 更新最新温度值
                        txtTemp.setText(value+"°C");
                        txtTime.setText(time);

                    }


                }
                drawChart(xValues,yValues);

            }catch (Exception e){
                e.printStackTrace();
            }



        }
    };

    private void drawChart(List<AxisValue> xValues, List<PointValue> yValues){
        // https://github.com/lecho/hellocharts-android



        Line line = new Line(yValues);
        line.setColor(Color.parseColor("#99cc00")); // 曲线的颜色
        line.setCubic(false); // 曲线是否平滑
        line.setHasLabels(true);//曲线的数据坐标是否加上备注

        // 把曲线加入到曲线集合里，一个图可以有很多曲线，这里只有一条
        List<Line> lines = new ArrayList<Line>();
        lines.add(line);

        // 把曲线数据转换为图表数据类型
        LineChartData data = new LineChartData();
        data.setLines(lines);

        // 添加坐标轴
        Axis axisX = new Axis();//x轴
        axisX.setName("时间");//x轴名称
        axisX.setHasLines(true); //网格线
        axisX.setHasTiltedLabels(true);//X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setValues(xValues);
        Axis axisY = new Axis();//y轴
        axisY.setName("温度");
        axisY.setHasLines(true);

        data.setAxisXBottom(axisX);
        data.setAxisYLeft(axisY);


        // 添加图表数据到图表里
        LineChartView chart = (LineChartView) findViewById(R.id.chart);
        chart.setInteractive(false);
        chart.setLineChartData(data);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temp);

        txtTemp=(TextView)findViewById(R.id.txt_temp_value);
        txtTime=(TextView)findViewById(R.id.txt_temp_time);




        new Thread(new Runnable() {
            @Override
            public void run() {


                // http://square.github.io/okhttp/
                try {


                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("https://leancloud.cn:443/1.1/classes/iot?limit=10&&order=updatedAt&&")
                            .addHeader("X-LC-Id"," ")
                            .addHeader("X-LC-Key"," ")
                            .build();

                    Response response = okHttpClient.newCall(request).execute();
                    String strResponseData = response.body().string();
                    // Log.v("data", strResponseData);

                    Message msg=new Message();
                    msg.obj=strResponseData;
                    handler.sendMessage(msg);



                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();



    }
}
